package com.shenzhen.horselive.ui.activity;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import android.Manifest;
import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.net.Uri;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Editable;
import android.text.TextUtils;
import android.text.TextWatcher;
import android.util.Pair;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.Toast;

import com.alipay.sdk.app.PayTask;
import com.flqy.baselibrary.utils.GlideHelper;
import com.flqy.baselibrary.utils.T;
import com.hjq.permissions.OnPermission;
import com.hjq.permissions.Permission;
import com.hjq.permissions.XXPermissions;
import com.shenzhen.horselive.MainActivity;
import com.shenzhen.horselive.R;
import com.shenzhen.horselive.User;
import com.shenzhen.horselive.api.ApiFactory;
import com.shenzhen.horselive.base.AppBarActivity;
import com.shenzhen.horselive.beans.FabuFanwei;
import com.shenzhen.horselive.beans.FabuGuanBoBean;
import com.shenzhen.horselive.beans.MessageEventWXPayresult;
import com.shenzhen.horselive.beans.PayResultBean;
import com.shenzhen.horselive.beans.PayWayBean;
import com.shenzhen.horselive.beans.SendRedRulersBean;
import com.shenzhen.horselive.common.SafeConsumer;
import com.shenzhen.horselive.common.utils.Permissions;
import com.shenzhen.horselive.common.utils.handler.IFilterHandler;
import com.shenzhen.horselive.databinding.ActivityBroadcastRedpacketsBinding;
import com.shenzhen.horselive.network.SchedulersCompat;
import com.shenzhen.horselive.presenter.LoadingViewObserver;
import com.shenzhen.horselive.utils.PayResult;
import com.shenzhen.horselive.widget.ZzImageBox;
import com.shenzhen.horselive.wx.WXManager;
import com.zhihu.matisse.Matisse;
import com.zhihu.matisse.MimeType;
import com.zhihu.matisse.engine.impl.GlideEngine;
import com.zhihu.matisse.filter.Filter;

import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.File;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import gun0912.tedbottompicker.PhotoPicker;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

public class BroadcastRedpacketsActivity extends AppBarActivity {

    private static final int REQUEST_CODE_CHOOSE =9001 ;
    ActivityBroadcastRedpacketsBinding  binding;

    private static final int SDK_PAY_FLAG = 1;
    private static final int SDK_AUTH_FLAG = 2;


    private  Handler  handler = new Handler(){
        @Override
        public void handleMessage(Message msg) {
            switch (msg.what)
            {
                case SDK_PAY_FLAG:
                    PayResult payResult = new PayResult((Map<String, String>) msg.obj);
                    /**
                     * 对于支付结果，请商户依赖服务端的异步通知结果。同步通知结果，仅作为支付结束的通知。
                     */
                    String resultInfo = payResult.getResult();// 同步返回需要验证的信息
                    String resultStatus = payResult.getResultStatus();
                    // 判断resultStatus 为9000则代表支付成功
                    if (TextUtils.equals(resultStatus, "9000")) {
                        // 该笔订单是否真实支付成功，需要依赖服务端的异步通知。
                        checkPayResult();
                    } else {
                        // 该笔订单真实的支付结果，需要依赖服务端的异步通知。 showAlert(PayDemoActivity.this, getString(R.string.pay_failed) + payResult);
                       showToast("支付取消");

                    }
                    break;
            }

            super.handleMessage(msg);
        }
    };

    //查询支付是否成功
    private void checkPayResult() {
        if (orderrCode==null||channelTag==null)
        {
            return;
        }
        //支付成功
        ApiFactory.getApiService().getPayResult(User.get().getMyInfo().getToken()
                ,orderrCode,channelTag
        ).compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<PayResultBean>(this) {
                    @Override
                    protected void onNextInActive(PayResultBean payResultBean) {
                        if (payResultBean.isSuccess()&&payResultBean.getData().getPayStatus()==1)
                        {
                            showToast("发送红包成功");
                            finish();
                        }
                        else {
                            showToast(payResultBean.getErrMessage());
                        }
                    }
                });

    }


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        binding = ActivityBroadcastRedpacketsBinding.inflate(getLayoutInflater());
        setContentView(binding.getRoot());
        setStyleDark();
        setTitle("广播红包");
        intiViews();
        initData();
    }




    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onMessageEvent(MessageEventWXPayresult event) {
       //微信支付的回调
        if (event.getCode()==0)
        {
            checkPayResult();
        }else
        {
            showToast("支付取消");
        }

    };

    double  maxAmount;
    double  minAmount;
    int  minNum;
    private void initData() {
        //获取发送的规则
        ApiFactory.getApiService().sendRedLimitRulers(User.get().getMyInfo().getToken())
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<SendRedRulersBean>(this) {
                    @Override
                    protected void onNextInActive(SendRedRulersBean sendRedRulersBean) {
                        if (sendRedRulersBean.isSuccess())
                        {
                            maxAmount = Double.parseDouble(sendRedRulersBean.getData().getMaxAmount());
                            minAmount = Double.parseDouble(sendRedRulersBean.getData().getMinAmount());
                            minNum = sendRedRulersBean.getData().getMinNum();
                           binding.tvTextSendAmountNotice.setText(String.format("（不可低于%s元,不可高于%s元）",minAmount+"",maxAmount+""));
                            binding.tvTextSendNumNotice.setText(String.format("（不可低于%s个）",minNum+""));
                        }
                    }
                });

        //支付渠道
      ApiFactory.getApiService().getPayWays(User.get().getMyInfo().getToken())
              .compose(SchedulersCompat.applyIoSchedulers())
              .safeSubscribe(new LoadingViewObserver<PayWayBean>(this) {
                  @Override
                  protected void onNextInActive(PayWayBean payWayBean) {
                      if (payWayBean.isSuccess())
                      {
                          binding.payviews.setList(payWayBean.getData());
                      }
                  }
              });

    }

    private void intiViews() {
        imgPaths=new ArrayList<>();
        binding.tcChooseAddr.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startActivityForResult(new Intent(BroadcastRedpacketsActivity.this,RedPackageLimitActivity.class),1000);
            }
        });

//        //添加图片
//        binding.imgThree.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                chooseImage();
//            }
//        });


        binding.linerPayGo.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                submit();
            }
        });

        //支付金额展示
        binding.etMoney.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
              String  money = s.toString();
              if (TextUtils.isEmpty(money))
              {
                  binding.tvFenzhiPay.setText("支付金额：¥ 0.00");

              }else
              {
                  binding.tvFenzhiPay.setText("支付金额：¥ "+money);
              }
            }
        });


      binding.zzImageBox.setOnImageClickListener(new ZzImageBox.AbsOnImageClickListener() {
          @Override
          public void onImageClick(int position, String url, String realPath, int realType, ImageView iv, String tag) {

          }

          @Override
          public void onAddClick() {
              super.onAddClick();
              chooseImage();
          }

          @Override
          public void onDeleteClick(int position, String url, String realPath, int realType, String tag) {
              super.onDeleteClick(position, url, realPath, realType, tag);
              binding.zzImageBox.removeImage(position);
          }
      });
    }

    String  orderrCode;
    String  channelTag;
    //支付红包
    private void submit() {
        String   content = binding.etText.getText();
        if (TextUtils.isEmpty(content))
        {
            showToast("请填写阐述");
            return;
        }
        if (binding.zzImageBox.getAllImages().size()==0)
        {
            showToast("请选择图片");
            return;
        }
        String  money = binding.etMoney.getText().toString();
        if (TextUtils.isEmpty(money))
        {
            showToast("请填写金额");
            return;
        }
        if (Double.parseDouble(money)<minAmount||Double.parseDouble(money)>maxAmount)
        {
            showToast("红包金额需在"+minAmount+"元至"+maxAmount+"元之间");
            return;
        }

        String  num = binding.etNum.getText().toString();
        if (TextUtils.isEmpty(num))
        {
            showToast("请填写红包个数");
            return;
        }
        if (Integer.parseInt(num)<minNum)
        {
            showToast("红包个数不能小于"+minNum+"个");
            return;
        }
        //领取范围
      if (fabuFanwei==null)
      {
          showToast("请选择红包发布范围");
          return;
      }

      if (binding.payviews.getPayWayItem()==null)
      {
          showToast("暂时没有可用的支付渠道");
          return;
      }


        MultipartBody.Builder multipartBody = new MultipartBody.Builder()
                .addFormDataPart("token", User.get().getMyInfo().getToken())
                .addFormDataPart("description", content)
                .addFormDataPart("channelId", binding.payviews.getPayWayItem().getChannelTag())
                .addFormDataPart("totalAmount", money)
                .addFormDataPart("quantity", num)
                .addFormDataPart("receiveRange", fabuFanwei.getRange()+"")
                .addFormDataPart("lng", fabuFanwei.getLng()+"")
                .addFormDataPart("lat", fabuFanwei.getLat()+"")
                .addFormDataPart("provinceCode",fabuFanwei.getProvenceCode())
                .addFormDataPart("provinceName",fabuFanwei.getProvence())
//                .addFormDataPart("cityName",fabuFanwei.getCity())
//                .addFormDataPart("cityCode",fabuFanwei.getCityCode())
//                .addFormDataPart("areaName",fabuFanwei.getDirect())
//                .addFormDataPart("areaCode",fabuFanwei.getDirectCode())
                .setType(MultipartBody.FORM);
        for (int i = 0; i <binding.zzImageBox.getAllImages().size(); i++) {
            File  file = new File(binding.zzImageBox.getAllImages().get(i));
            RequestBody fileBody = RequestBody.create(MediaType.parse("multipart/form-data"), file);
           multipartBody.addFormDataPart("files", file.getName(), fileBody);
        }
        ApiFactory.getApiService().fabuGuangboRed(multipartBody.build())
                .compose(SchedulersCompat.applyIoSchedulers())
                .safeSubscribe(new LoadingViewObserver<FabuGuanBoBean>(this) {
                    @Override
                    protected void onNextInActive(FabuGuanBoBean fabuGuanBoBean) {
                        if (fabuGuanBoBean.isSuccess())
                        {
                            orderrCode = fabuGuanBoBean.getData().getOrderCode();
                            channelTag = binding.payviews.getPayWayItem().getChannelTag();
                           //掉起支付
                            if (binding.payviews.getPayWayItem().getChannelName().contains("微信"))
                            {
                                WXManager.getInstance().goToPay(fabuGuanBoBean.getData().getPayResult());
                            }else  if (binding.payviews.getPayWayItem().getChannelName().contains("支付宝"))
                            {
                                Runnable payRunnable = new Runnable() {

                                    @Override
                                    public void run() {
                                        PayTask alipay = new PayTask(BroadcastRedpacketsActivity.this);
                                        Map<String,String> result = alipay.payV2(fabuGuanBoBean.getData().getPayResult(),true);
                                        Message msg = new Message();
                                        msg.what = SDK_PAY_FLAG;
                                        msg.obj = result;
                                        handler.sendMessage(msg);
                                    }
                                };
                                // 必须异步调用
                                Thread payThread = new Thread(payRunnable);
                                payThread.start();

                            }
                        }else
                        {
                            showToast(fabuGuanBoBean.getErrMessage());
                        }
                    }
                });
    }

    List<String>  imgPaths;
    //选择照片
    private void chooseImage() {
        XXPermissions.with(this)
                .permission(Permission.Group.STORAGE)
                .request(new OnPermission() {
                    @Override
                    public void hasPermission(List<String> granted, boolean all) {
                        if (all)
                        {

                            Matisse.from(BroadcastRedpacketsActivity.this)
                                    .choose(MimeType.ofImage())
                                    .countable(false)
                                    .maxSelectable(1)
                                    .showSingleMediaType(true)
//                                    .addFilter(new GifSizeFilter(320, 320, 5 * Filter.K * Filter.K))
//                                    .gridExpectedSize(getResources().getDimensionPixelSize(R.dimen.grid_expected_size))
//                                    .restrictOrientation(ActivityInfo.SCREEN_ORIENTATION_UNSPECIFIED)
//                                    .thumbnailScale(0.85f)
                                    .imageEngine(new GlideEngine())
//                                    .showPreview(false) // Default is `true`
                                    .forResult(REQUEST_CODE_CHOOSE);


                            //权限申请成功
//                            new PhotoPicker.Builder(BroadcastRedpacketsActivity.this).setSelectMaxCount(1)
//                                    .setOnImageSelectedListener(new PhotoPicker.OnImageSelectedListener() {
//                                        @Override
//                                        public void onImageSelected(Pair<Uri, String> imagePath) {
//                                            binding.zzImageBox.addImage(imagePath.second);
//                                        }
//                                    }).create().show();


                        }
                    }

                    @Override
                    public void noPermission(List<String> denied, boolean quick) {

                    }
                });

    }

    FabuFanwei  fabuFanwei;
    List<String>  mSelected;
    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode==1000&&resultCode==1001)
        {
           fabuFanwei = (FabuFanwei) data.getSerializableExtra("data");
            binding.tcChooseAddr.setText(fabuFanwei.getName());
        }

        if (requestCode == REQUEST_CODE_CHOOSE && resultCode == RESULT_OK) {
//            mSelected = Matisse.obtainResult(data);
          mSelected =   Matisse.obtainPathResult(data);
          if (mSelected!=null&&mSelected.size()>0)
          {
           binding.zzImageBox.addImage(mSelected.get(0));
          }
        }
    }



}